﻿Public Class FrmCompras

    Private Sub FrmCompras_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Me.dgvdetalle.AutoGenerateColumns = False
        Me.llenarCombos()
        Me.CargarCompras()
    End Sub

    Dim controller As New Class_RC_Controller.rc_Facturas
    Dim proveedores As New Class_RC_Controller.rc_Proveedores
    Dim mante As New Class_RC_Controller.rc_Mantenimiento
    Dim materiales As New Class_RC_Controller.rc_Materiales
    Dim ordenes As New Class_RC_Controller.rc_OrdenCompra

    Private _codOrden As Integer = 0

    Public Property codOrden() As Integer
        Get
            Return _codOrden
        End Get
        Set(value As Integer)
            _codOrden = value
        End Set
    End Property

    Private _codFactura As Integer = 0

    Public Property codCompra() As Integer
        Get
            Return _codFactura
        End Get
        Set(value As Integer)
            _codFactura = value
            txtcodigo.Text = value.ToString().PadLeft(4, "0")
        End Set
    End Property

    Private Sub llenarCombos()

        Me.cboTipo.SelectedIndex = 1
        Me.cboEstado.SelectedIndex = 1
        Me.cboIVA.SelectedIndex = 2

        Dim ds As DataTable
        ds = proveedores.get_Proveedores_All(oiml.dbConn, 0, "", "", 0)
        With Me.cboProveedor
            .DataSource = ds
            .DisplayMember = "nombre"
            .ValueMember = "codProveedor"
        End With

        Dim dsTipo As DataTable
        dsTipo = materiales.get_tipo_Materiales(oiml.dbConn)
        With Me.cboTipoMaterial
            .DataSource = dsTipo
            .DisplayMember = "descTipoMaterial"
            .ValueMember = "codTipoMaterial"
        End With

        CargarMAteriales()

    End Sub

    Private Sub CargarMAteriales()

        Dim codTipoMaterial As Integer = 0

        If cbxTipo.Checked And IsNumeric(cboTipoMaterial.SelectedValue) Then
            codTipoMaterial = cboTipoMaterial.SelectedValue

            Dim dt As New DataTable
            dt = materiales.get_Materiales_All(oiml.dbConn, 0, txtMaterial.Text, codTipoMaterial)
            If Not dt Is Nothing Then

                With Me.cboMaterial
                    .DataSource = dt
                    .DisplayMember = "DescMaterial"
                    .ValueMember = "codMaterial"
                End With

                SeleccionarMaterial()
            Else
                cboMaterial.DataSource = Nothing
            End If

        End If

    End Sub

    Private Sub CargarMateriales_ByID(codMaterial As Integer)

        Dim dt As New DataTable
        'dt = materiales.get_Materiales_All(oiml.dbConn, codMaterial, "", 0, 0)

        If Not dt Is Nothing Then

            'If IsNumeric(dt.Rows(0)("PrecioVenta").ToString()) Then
            '    txtprecio.Text = Decimal.Parse(dt.Rows(0)("PrecioVenta").ToString())
            'Else
            '    txtprecio.Text = 0
            'End If

        Else
            'txtprecio.Text = 0
        End If

    End Sub

    Private Sub CargarDetalles()
        If codCompra > 0 Then

            Dim dt As New DataTable
            dt = controller.get_Compras_Detalles_All(oiml.dbConn, codCompra)
            
            If Not dt Is Nothing Then
                dgvdetalle.DataSource = dt
                cboTipo.Enabled = False
                txtOrden.ReadOnly = True
                btnOrden.Enabled = False
                cboProveedor.Enabled = False

                If dgvdetalle.Rows.Count > 0 And codOrden > 0 Then
                    dgvdetalle.Rows(0).Selected = True
                    If dgvdetalle.SelectedRows.Count > 0 Then
                        CargarComprasDetalle(dgvdetalle.SelectedRows(0).Cells(1).Value)
                    End If

                End If

            Else
                dgvdetalle.DataSource = Nothing
                cboTipo.Enabled = True
                txtOrden.ReadOnly = False
                btnOrden.Enabled = True
                cboProveedor.Enabled = True
            End If

        End If

    End Sub

    Private Sub CargarCompras()
        Try
            If codCompra > 0 Then

                Dim ds As New DataTable
                ds = controller.get_Compras_ByID(oiml.dbConn, codCompra)

                If Not ds Is Nothing Then

                    ' cargar los controles del formulario con los valores de los campos del registro
                    codCompra = ds.Rows(0)("codCompra").ToString
                    Me.nroFactura.Text = ds.Rows(0)("nroFactura").ToString
                    Me.fechaFactura.Value = DateTime.Parse(ds.Rows(0)("fecha").ToString())

                    If ds.Rows(0)("vencimiento_").ToString <> "" Then
                        Me.fechaVto.Value = DateTime.Parse(ds.Rows(0)("vencimiento").ToString())
                    End If

                    Me.cboTipo.Text = ds.Rows(0)("tipoCompra").ToString
                    Me.cboEstado.Text = ds.Rows(0)("estadoCompra").ToString
                    'Me.cboVendedor.SelectedValue = ds.Rows(0)("codVendedor").ToString

                    If ds.Rows(0)("totalCompra").ToString <> "" Then
                        Me.txtTotalFactura.Text = Decimal.Parse(ds.Rows(0)("totalCompra").ToString()).ToString("N0")
                    End If

                    If ds.Rows(0)("totalCompraSaldo").ToString <> "" Then
                        Me.txtSaldo.Text = Decimal.Parse(ds.Rows(0)("totalCompraSaldo").ToString()).ToString("N0")

                        If (Decimal.Parse(ds.Rows(0)("totalCompraSaldo").ToString()) <
                            Decimal.Parse(ds.Rows(0)("totalCompra").ToString)) Then

                            btnEliminar.Enabled = False
                            btnAnular.Enabled = False

                            nroFactura.Enabled = False
                            fechaFactura.Enabled = False
                            fechaVto.Enabled = False
                            btnGrabar.Enabled = False
                            btnAgregarDetalle.Enabled = False
                            btnEliminarDetalle.Enabled = False
                            txtMaterial.Enabled = False
                            cboMaterial.Enabled = False
                            txtcantidad.Enabled = False
                            txtprecio.Enabled = False
                            cboIVA.Enabled = False
                            cboTipoMaterial.Enabled = False

                        Else

                            btnEliminar.Enabled = True
                            btnAnular.Enabled = True

                            nroFactura.Enabled = True
                            fechaFactura.Enabled = True
                            fechaVto.Enabled = True
                            btnGrabar.Enabled = True
                            btnAgregarDetalle.Enabled = True
                            btnEliminarDetalle.Enabled = True
                            txtMaterial.Enabled = True
                            cboMaterial.Enabled = True
                            txtcantidad.Enabled = True
                            txtprecio.Enabled = True
                            cboIVA.Enabled = True
                            cboTipoMaterial.Enabled = True

                        End If

                    End If

                    If ds.Rows(0)("totalCompraIVA").ToString <> "" Then
                        Me.txtIVA.Text = Decimal.Parse(ds.Rows(0)("totalCompraIVA").ToString()).ToString("N0")
                    End If

                    If ds.Rows(0)("codOrden").ToString <> "" And ds.Rows(0)("nroOrdenCompra").ToString <> "" Then
                        codOrden = Integer.Parse(ds.Rows(0)("codOrden").ToString)
                        txtOrden.Text = ds.Rows(0)("nroOrdenCompra").ToString
                        txtOrden.ReadOnly = True
                        btnOrden.Enabled = False
                        txtcantidad.ReadOnly = True
                        btnEliminarDetalle.Enabled = False
                        btnAgregarDetalle.Text = "&Actualizar"
                    Else
                        codOrden = 0
                        txtOrden.Text = ""
                        txtOrden.ReadOnly = False
                        btnOrden.Enabled = True
                        txtcantidad.ReadOnly = False
                        btnEliminarDetalle.Enabled = True
                        btnAgregarDetalle.Text = "&Agregar"
                    End If

                    Me.cboProveedor.SelectedValue = ds.Rows(0)("codProveedor").ToString

                    Me.lblUsuario.Text = ds.Rows(0)("usuario").ToString
                    Me.lblfechaActualizacion.Text = ds.Rows(0)("fechaActualizacion_").ToString

                    CargarDetalles()
                    ControlEstado()

                End If

            Else

                ' cargar los controles del formulario con los valores de los campos del registro
                codCompra = 0
                Me.nroFactura.Text = ""
                Me.fechaFactura.Value = DateTime.Now
                Me.fechaVto.Value = DateTime.Now

                Me.cboTipo.SelectedIndex = 0
                Me.cboTipoMaterial.SelectedIndex = 0
                Me.cboIVA.SelectedIndex = 0
                Me.cboEstado.SelectedIndex = 0

                Me.txtTotalFactura.Text = 0
                Me.txtSaldo.Text = 0
                Me.txtIVA.Text = 0

                Me.cboProveedor.SelectedIndex = 0

                lblUsuario.Text = oiml.Usuario
                lblfechaActualizacion.Text = Date.Now.ToShortDateString

                fechaFactura.Focus()

            End If

        Catch ex As Exception
            MessageBox.Show("Error: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

        End Try

    End Sub

    Private Sub CargarComprasDetalle(codMaterial As Integer)
        Try
            If codCompra > 0 And codMaterial > 0 Then

                Dim ds As New DataTable
                ds = controller.get_Compras_Detalles_ByID(oiml.dbConn, codCompra, codMaterial)

                If Not ds Is Nothing Then

                    cboTipoMaterial.SelectedValue = ds.Rows(0)("codTipoMaterial").ToString
                    CargarMAteriales()
                    cboMaterial.SelectedValue = ds.Rows(0)("CodMaterial").ToString
                    txtcantidad.Text = ds.Rows(0)("cantidad").ToString

                    If codOrden > 0 Then
                        txtcantidad.ReadOnly = True
                    Else
                        txtcantidad.ReadOnly = False
                    End If

                End If

            End If

        Catch ex As Exception
            MessageBox.Show("Error: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

        End Try

    End Sub

    Private Sub ControlEstado()
        If Me.cboEstado.Text = "APROBADA" Or Me.cboEstado.Text = "ANULADA" Then
            grbCabecera.Enabled = False
            grbDetalle.Enabled = False
        Else

            'If controller.Update_Compras(oiml.dbConn, codCompra, nroFactura.Text, fechaFactura.Value, "", cboTipo.Text, cboEstado.Text,
            '                            Decimal.Parse(txtTotalFactura.Text), Decimal.Parse(txtSaldo.Text), Decimal.Parse(txtIVA.Text), cboProveedor.SelectedValue,
            '                            oiml.idUsuario, 0) = False Then
            '    MessageBox.Show("Error: " & controller.MessageError.Message, "Compras", MessageBoxButtons.OK, MessageBoxIcon.Error)
            '    Exit Sub
            'End If

        End If
    End Sub

    Private Shadows Sub KeyUpmask(ByVal MaskedTextboxs As System.Windows.Forms.MaskedTextBox, ByVal e As System.Windows.Forms.KeyEventArgs)

        'Teclas que Utilizaremos El cual solo son las numericas
        If e.KeyData = Keys.Space Or e.KeyData = Keys.Decimal Or _
         e.KeyData = Keys.NumPad0 Or e.KeyData = Keys.NumPad1 Or e.KeyData = Keys.NumPad2 Or e.KeyData = Keys.NumPad3 _
           Or e.KeyData = Keys.NumPad4 Or e.KeyData = Keys.NumPad5 Or e.KeyData = Keys.NumPad6 Or _
           e.KeyData = Keys.NumPad7 Or e.KeyData = Keys.NumPad8 Or e.KeyData = Keys.NumPad9 _
           Or e.KeyData = Keys.D0 Or e.KeyData = Keys.D1 Or e.KeyData = Keys.D2 Or e.KeyData = Keys.D3 Or _
           e.KeyData = Keys.D4 Or e.KeyData = Keys.D5 Or e.KeyData = Keys.D6 _
           Or e.KeyData = Keys.D7 Or e.KeyData = Keys.D8 Or e.KeyData = Keys.D9 Or e.KeyData = Keys.Tab Or e.KeyData = Keys.Enter _
            Then

            'Programamos la tecla de Retroceso en el textbox
        ElseIf e.KeyData = Keys.Back And MaskedTextboxs.Text.Length > 0 Then
            On Error Resume Next
            'Removemos un caracter mediante se presione la tecla Back
            MaskedTextboxs.Text.Remove(MaskedTextboxs.SelectionStart - 1)

            'si el textbox es menor que un caracter
        ElseIf MaskedTextboxs.Text.Length < 1 Then
            'ponemos el textbox En Blanco
            MaskedTextboxs.Text = String.Empty
            'ponemos la variable    NumerosYaescritos en Blanco

        Else
            'ponemos el textbox enblanco
            MaskedTextboxs.Text = String.Empty
            'Hacemos Sonar un Beep para indicarle al usuario que ha presionado un caracter y no un Numero
            Beep()
            MsgBox("Introducir solo valores numericos")
        End If

    End Sub

    Private Shadows Sub KeyUp(ByVal TextBoxs As System.Windows.Forms.TextBox, ByVal e As System.Windows.Forms.KeyEventArgs)

        'Teclas que Utilizaremos El cual solo son las numericas
        If e.KeyData = Keys.Space Or e.KeyData = Keys.Decimal Or _
         e.KeyData = Keys.NumPad0 Or e.KeyData = Keys.NumPad1 Or e.KeyData = Keys.NumPad2 Or e.KeyData = Keys.NumPad3 _
           Or e.KeyData = Keys.NumPad4 Or e.KeyData = Keys.NumPad5 Or e.KeyData = Keys.NumPad6 Or _
           e.KeyData = Keys.NumPad7 Or e.KeyData = Keys.NumPad8 Or e.KeyData = Keys.NumPad9 _
           Or e.KeyData = Keys.D0 Or e.KeyData = Keys.D1 Or e.KeyData = Keys.D2 Or e.KeyData = Keys.D3 Or _
           e.KeyData = Keys.D4 Or e.KeyData = Keys.D5 Or e.KeyData = Keys.D6 _
           Or e.KeyData = Keys.D7 Or e.KeyData = Keys.D8 Or e.KeyData = Keys.D9 Or e.KeyData = Keys.Tab Or e.KeyData = Keys.Enter _
           Or e.KeyData = Keys.OemMinus Then

            'Programamos la tecla de Retroceso en el textbox
        ElseIf e.KeyData = Keys.Back And TextBoxs.Text.Length > 0 Then
            On Error Resume Next
            'Removemos un caracter mediante se presione la tecla Back
            TextBoxs.Text.Remove(TextBoxs.SelectionStart - 1)

            'si el textbox es menor que un caracter
        ElseIf TextBoxs.Text.Length < 1 Then
            'ponemos el textbox En Blanco
            TextBoxs.Text = String.Empty
            'ponemos la variable    NumerosYaescritos en Blanco

        Else
            'ponemos el textbox enblanco
            TextBoxs.Text = String.Empty
            'Hacemos Sonar un Beep para indicarle al usuario que ha presionado un caracter y no un Numero
            Beep()
            MsgBox("Introducir solo valores numericos")
        End If

    End Sub

    Private Function ValidarCampos() As Boolean

        Dim controlCampos As Boolean = False

        If nroFactura.Text = "" Then
            ErrorProvider.SetError(nroFactura, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider.SetError(nroFactura, "")
        End If

        If fechaFactura.Value.ToString = "" Then
            ErrorProvider.SetError(fechaFactura, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider.SetError(fechaFactura, "")
        End If
        '
        Return controlCampos

    End Function

    Private Function ValidarDetallesCampos() As Boolean

        Dim controlCampos As Boolean = False

        If Not IsNumeric(txtcantidad.Text) Then
            ErrorProvider.SetError(txtcantidad, "Campo numerico, cantidad")
            controlCampos = True
        Else
            ErrorProvider.SetError(txtcantidad, "")
        End If        '

        If Not IsNumeric(txtprecio.Text) Then
            txtprecio.Text = 0
            'ErrorProvider.SetError(txtprecio, "Campo numerico, cantidad")
            'controlCampos = True
        Else
            ErrorProvider.SetError(txtprecio, "")
        End If

        If codOrden > 0 Then
            If dgvdetalle.SelectedRows.Count = 0 Then
                ErrorProvider.SetError(dgvdetalle, "Debe seleccionar un registro")
                controlCampos = True
            Else
                ErrorProvider.SetError(dgvdetalle, "")
            End If
        End If
        '
        Return controlCampos

    End Function

    Private Sub btncancelar_Click(sender As System.Object, e As System.EventArgs) Handles btnCancelar.Click
        Me.Close()
    End Sub

    Private Sub btnAgregarDetalle_Click(sender As System.Object, e As System.EventArgs) Handles btnAgregarDetalle.Click
        Try
            Dim fechaVtoValor As String = ""
            If cbxVto.Checked Then
                fechaVtoValor = fechaVto.Value.ToString
            End If

            If ValidarDetallesCampos() Then
                MessageBox.Show("Falta llenar datos del detalle", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1)
                txtcantidad.Focus()
            Else

                If codCompra = 0 Then

                    If ValidarCampos() Then
                        nroFactura.Focus()
                        Exit Sub
                    Else

                        codCompra = controller.Insert_Compras(oiml.dbConn, nroFactura.Text, fechaFactura.Value, fechaVtoValor, cboTipo.Text, cboEstado.Text,
                                        Decimal.Parse(txtTotalFactura.Text), Decimal.Parse(txtSaldo.Text), Decimal.Parse(txtIVA.Text), cboProveedor.SelectedValue,
                                        oiml.idUsuario, 0)

                        If codCompra = 0 Then
                            MessageBox.Show("Error: " & controller.MessageError.Message, "Compras", MessageBoxButtons.OK, MessageBoxIcon.Error)
                            Exit Sub
                        End If

                    End If

                Else

                    If ValidarCampos() Then
                        nroFactura.Focus()
                        Exit Sub
                    Else

                        If controller.Update_Compras(oiml.dbConn, codCompra, nroFactura.Text, fechaFactura.Value, fechaVtoValor, cboTipo.Text, cboEstado.Text,
                                        Decimal.Parse(txtTotalFactura.Text), Decimal.Parse(txtSaldo.Text), Decimal.Parse(txtIVA.Text), cboProveedor.SelectedValue,
                                        oiml.idUsuario, 0) = False Then
                            MessageBox.Show("Error: " & controller.MessageError.Message, "Compras", MessageBoxButtons.OK, MessageBoxIcon.Error)
                            Exit Sub
                        End If

                    End If

                End If

                Dim ivaMonto As Decimal = 0
                Dim iva As Decimal = 0
                Dim total As Decimal = Decimal.Parse(txttotal.Text)

                If cboIVA.Text.ToString = "05%" Then
                    ivaMonto = total / 21
                    iva = 5
                ElseIf cboIVA.Text.ToString = "10%" Then
                    ivaMonto = total / 11
                    iva = 10
                End If

                If codCompra > 0 Then
                    If controller.Insert_Compras_Detalle(oiml.dbConn, codCompra, cboMaterial.SelectedValue, Decimal.Parse(txtcantidad.Text),
                                                        Decimal.Parse(txtprecio.Text), iva,
                                                        ivaMonto, Decimal.Parse(txttotal.Text), Integer.Parse(cboProveedor.SelectedValue),
                                                        cboTipo.Text, oiml.idUsuario, codOrden) Then
                        CargarCompras()

                        If codOrden = 0 Then
                            limpiarDetalles()
                        End If


                    Else
                        MessageBox.Show("Error: " & controller.MessageError.Message, "Compras", MessageBoxButtons.OK, MessageBoxIcon.Error)

                    End If

                End If

            End If

        Catch ex As Exception
            MsgBox(ex.Message)

        End Try

    End Sub

    Private Function btnAgregarDetalle_Click(ivaText As String, total As Decimal, codProducto As Integer, cantidad As Decimal, precio As Decimal) As Boolean
        Try
            Dim fechaVtoValor As String = ""
            If cbxVto.Checked Then
                fechaVtoValor = fechaVto.Value.ToString
            End If

            If codCompra = 0 Then

                If ValidarCampos() Then
                    nroFactura.Focus()
                    Return False
                Else

                    codCompra = controller.Insert_Compras(oiml.dbConn, nroFactura.Text, fechaFactura.Value, fechaVtoValor, cboTipo.Text, cboEstado.Text,
                                    Decimal.Parse(txtTotalFactura.Text), Decimal.Parse(txtSaldo.Text), Decimal.Parse(txtIVA.Text), cboProveedor.SelectedValue,
                                    oiml.idUsuario, codOrden)

                    If codCompra = 0 Then
                        MessageBox.Show("Error: " & controller.MessageError.Message, "Compras", MessageBoxButtons.OK, MessageBoxIcon.Error)
                        Return False
                    End If

                End If

            Else

                If ValidarCampos() Then
                    nroFactura.Focus()
                    Return False
                Else

                    If controller.Update_Compras(oiml.dbConn, codCompra, nroFactura.Text, fechaFactura.Value, fechaVtoValor, cboTipo.Text, cboEstado.Text,
                                    Decimal.Parse(txtTotalFactura.Text), Decimal.Parse(txtSaldo.Text), Decimal.Parse(txtIVA.Text), cboProveedor.SelectedValue,
                                    oiml.idUsuario, codOrden) = False Then
                        MessageBox.Show("Error: " & controller.MessageError.Message, "Compras", MessageBoxButtons.OK, MessageBoxIcon.Error)
                        Return False
                    End If

                End If

            End If

            Dim ivaMonto As Decimal = 0
            Dim iva As Decimal = 0
            'Dim total As Decimal = Decimal.Parse(txttotal.Text)

            If ivaText = "05%" Then
                ivaMonto = total / 21
                iva = 5
            ElseIf ivaText = "10%" Then
                ivaMonto = total / 11
                iva = 10
            End If

            If codCompra > 0 Then
                If controller.Insert_Compras_Detalle(oiml.dbConn, codCompra, codProducto, cantidad,
                                                    precio, iva, ivaMonto, total, Integer.Parse(cboProveedor.SelectedValue),
                                                    cboTipo.Text, oiml.idUsuario, 0) Then
                    Return True

                Else
                    MessageBox.Show("Error: " & controller.MessageError.Message, "Compras", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    Return False
                End If

            End If

        Catch ex As Exception
            MsgBox(ex.Message)
            Return False
        End Try

    End Function

    Public Sub limpiarDetalles()
        txtcantidad.Text = 1
        txtprecio.Text = 0
        txttotal.Text = 0
        txtMaterial.Text = ""
    End Sub

    'Private Sub totales()
    '    Dim i As Integer
    '    For i = 0 To dgvdetalle.Rows.Count - 1
    '        totalpres += CDec(dgvdetalle.Rows(i).Cells(8).Value)
    '    Next
    '    txttotalmano.Text = FormatNumber(totalpres, 0, , , TriState.True)
    'End Sub

    Private Sub btnEliminarDetalle_Click(sender As System.Object, e As System.EventArgs) Handles btnEliminarDetalle.Click
        Try
            If dgvdetalle.SelectedRows.Count > 0 Then
                Dim codDetalle As Integer
                codDetalle = dgvdetalle.SelectedRows(0).Cells(1).Value

                If codDetalle > 0 And MessageBox.Show("Desea eliminar el registro seleccionado?", "Compras", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

                    If controller.Delete_Compras_Detalle(oiml.dbConn, codCompra, codDetalle, oiml.idUsuario) Then
                        CargarCompras()
                        dgvdetalle.Refresh()

                    Else
                        MessageBox.Show("Error: " & controller.MessageError.Message, "Compras", MessageBoxButtons.OK, MessageBoxIcon.Error)

                    End If

                End If

            End If

        Catch ex As Exception
            MsgBox(ex.Message)

        End Try

    End Sub

    Private Sub btnGrabar_Click(sender As System.Object, e As System.EventArgs) Handles btnGrabar.Click

        If ValidarCampos() Then
            nroFactura.Focus()
            Exit Sub
        End If
        ordenes.Update_OrdenCompra_Estado(oiml.dbConn, codOrden, "APROBADA", oiml.idUsuario)

        Dim fechaVtoValor As String = ""
        If cbxVto.Checked Then
            fechaVtoValor = fechaVto.Value.ToString
        End If

        If codCompra = 0 Then

            codCompra = controller.Insert_Compras(oiml.dbConn, nroFactura.Text, fechaFactura.Value, fechaVtoValor, cboTipo.Text, cboEstado.Text,
                                        Decimal.Parse(txtTotalFactura.Text), Decimal.Parse(txtSaldo.Text), Decimal.Parse(txtIVA.Text), cboProveedor.SelectedValue,
                                        oiml.idUsuario, 0)

            If codCompra > 0 Then
                MessageBox.Show("Registro grabado con exito!", "Compras", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                Me.DialogResult = Windows.Forms.DialogResult.OK
                CargarCompras()

            Else
                MessageBox.Show("Error: " & controller.MessageError.Message, "Compras", MessageBoxButtons.OK, MessageBoxIcon.Error)

            End If

        Else
            If controller.Update_Compras(oiml.dbConn, codCompra, nroFactura.Text, fechaFactura.Value, fechaVtoValor, cboTipo.Text, cboEstado.Text,
                                        Decimal.Parse(txtTotalFactura.Text), Decimal.Parse(txtSaldo.Text), Decimal.Parse(txtIVA.Text), cboProveedor.SelectedValue,
                                        oiml.idUsuario, 0) Then

                MessageBox.Show("Registro grabado con exito!", "Compras", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                Me.DialogResult = Windows.Forms.DialogResult.OK
                CargarCompras()

            Else
                MessageBox.Show("Error: " & controller.MessageError.Message, "Compras", MessageBoxButtons.OK, MessageBoxIcon.Error)

            End If

        End If

    End Sub

    Private Sub btneliminar_Click(sender As System.Object, e As System.EventArgs) Handles btnEliminar.Click

        Try
            If codCompra > 0 Then
                If MessageBox.Show("Desea eliminar el registro seleccionado?", "Compras", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

                    If controller.Delete_Compras(oiml.dbConn, codCompra, oiml.idUsuario) Then
                        Me.Close()

                    Else
                        MessageBox.Show("Error: " & controller.MessageError.Message, "Compras", MessageBoxButtons.OK, MessageBoxIcon.Error)

                    End If

                End If
            End If


        Catch ex As Exception
            MsgBox(ex.Message)

        End Try

    End Sub

    Private Sub txtprecio_Leave(sender As System.Object, e As System.EventArgs) Handles txtprecio.Leave

        If ValidarDetallesCampos() Then
            txtprecio.Focus()
        Else
            txttotal.Text = Decimal.Parse(txtcantidad.Text) * Decimal.Parse(txtprecio.Text)
        End If

    End Sub

    Private Sub txtcantidad_Leave(sender As System.Object, e As System.EventArgs) Handles txtcantidad.Leave

        If ValidarDetallesCampos() Then
            txtcantidad.Focus()
        Else
            txttotal.Text = Decimal.Parse(txtcantidad.Text) * Decimal.Parse(txtprecio.Text)
        End If

    End Sub

    Private Sub cbxTipo_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles cbxTipo.CheckedChanged
        CargarMAteriales()
    End Sub

    Private Sub cboTipoProducto_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles cboTipoMaterial.KeyDown
        If e.KeyCode = Keys.Enter Then
            CargarMAteriales()
        End If
    End Sub

    Private Sub txtProducto_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles txtMaterial.KeyDown
        If e.KeyCode = Keys.Enter Then
            CargarMAteriales()
        End If
    End Sub

    Private Sub cboProducto_SelectedpValueChanged(sender As System.Object, e As System.EventArgs) Handles cboMaterial.SelectedValueChanged

        SeleccionarMaterial()

    End Sub

    Private Sub SeleccionarMaterial()
        If Not cboMaterial.SelectedValue Is Nothing Then
            If cboMaterial.SelectedValue.ToString <> "System.Data.DataRowView" Then
                CargarMateriales_ByID(cboMaterial.SelectedValue)
            End If
        End If

    End Sub

    Private Sub cbxVto_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles cbxVto.CheckedChanged
        fechaVto.Enabled = cbxVto.Checked
    End Sub

    Private Sub cboTipoMaterial_SelectedValueChanged(sender As System.Object, e As System.EventArgs) Handles cboTipoMaterial.SelectedValueChanged

        CargarMAteriales()

    End Sub

    Private m_frmRpts As FormReportes
    Public Property frmRpts() As FormReportes
        Get
            Return m_frmRpts
        End Get
        Set(value As FormReportes)
            m_frmRpts = value
        End Set
    End Property

    'Private Sub btnImprimir_Click(sender As System.Object, e As System.EventArgs) Handles btnImprimir.Click


    '    Dim dt As New DataTable
    '    dt = controller.get_Compras_Producto_ByID(oiml.dbConn, codCompra)

    '    If frmRpts Is Nothing Then
    '        frmRpts = New FormReportes()
    '        'frmRpts.MdiParent = Me
    '        frmRpts.tipo_Reporte = "FACTURAS"
    '        frmRpts.datos_Reporte = dt
    '        frmRpts.ShowDialog()
    '    Else

    '        If Not frmRpts.Visible Then
    '            frmRpts = New FormReportes()
    '            'frmRpts.MdiParent = Me
    '            frmRpts.tipo_Reporte = "FACTURAS"
    '            frmRpts.datos_Reporte = dt
    '            frmRpts.ShowDialog()
    '        Else
    '            frmRpts.tipo_Reporte = "FACTURAS"
    '            frmRpts.datos_Reporte = dt
    '            frmRpts.Select()
    '            frmRpts.Activate()
    '        End If

    '    End If

    '    If Not controller.MessageError Is Nothing Then
    '        MessageBox.Show("Error: " & controller.MessageError.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    '    End If

    'End Sub

    

    Private Sub btnAnular_Click(sender As System.Object, e As System.EventArgs) Handles btnAnular.Click
        Try
            If codCompra > 0 Then
                If MessageBox.Show("Desea anular el registro seleccionado?", "Compras", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

                    If controller.Update_Compras_Estado(oiml.dbConn, codCompra, "ANULADA", oiml.idUsuario) Then
                        Me.Close()

                    Else
                        MessageBox.Show("Error: " & controller.MessageError.Message, "Compras", MessageBoxButtons.OK, MessageBoxIcon.Error)

                    End If

                End If
            End If


        Catch ex As Exception
            MsgBox(ex.Message)

        End Try
    End Sub

    Private Sub txtOrden_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles txtOrden.KeyDown
        If e.KeyCode = Keys.Enter Then
            btnOrden_Click(sender, e)
        End If
    End Sub

    Private Sub txtcantidad_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtcantidad.TextChanged

    End Sub

    Private Sub cboProveedor_SelectedValueChanged(sender As System.Object, e As System.EventArgs) Handles cboProveedor.SelectedValueChanged
        CargarMAteriales()

    End Sub

    Private Sub btnOrden_Click(sender As System.Object, e As System.EventArgs) Handles btnOrden.Click
        Try
            If txtOrden.Text = "" Then
                Return
            End If

            If ValidarCampos() Then
                nroFactura.Focus()
                Exit Sub
            End If

            Dim dt As New DataTable
            dt = ordenes.get_OrdenCompra_ByNRO(oiml.dbConn, txtOrden.Text, True)

            If Not dt Is Nothing Then

                'And dt.Rows.Count > 0

                codOrden = dt.Rows(0)("codOrdenCompra").ToString

                Dim dtDetalle As New DataTable
                dtDetalle = ordenes.get_OrdenCompra_Detalles_All(oiml.dbConn, codOrden)

                If Not dt Is Nothing And dt.Rows.Count > 0 Then

                    If MessageBox.Show("Desea cargar la orden de compra nro. " & txtOrden.Text & "?", "Ordenes de compra", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

                        cboProveedor.SelectedValue = dt.Rows(0)("codProveedor").ToString

                        Dim total As Decimal = 0
                        Dim codMaterial As Integer = 0
                        Dim ivaCodigo As String = "10%"
                        For i As Integer = 0 To dtDetalle.Rows.Count - 1

                            codMaterial = dtDetalle.Rows(i)("codMaterial")

                            If Not btnAgregarDetalle_Click(ivaCodigo, total, codMaterial, dtDetalle.Rows(i)("cantidad"), 0) Then
                                Return
                            End If

                        Next

                        CargarCompras()
                        MessageBox.Show("Registro grabado con exito!", "Compras", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

                    End If

                End If

            Else
                MessageBox.Show("Orden de compra no encontrada o ya ha sido facturada.", "Ordenes de compra", MessageBoxButtons.OK, MessageBoxIcon.Information)

            End If

        Catch ex As Exception
            MessageBox.Show("Error: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

        End Try
    End Sub

    Private Sub dgvdetalle_DoubleClick(sender As System.Object, e As System.EventArgs) Handles dgvdetalle.DoubleClick
        If dgvdetalle.SelectedRows.Count > 0 Then
            CargarComprasDetalle(dgvdetalle.SelectedRows(0).Cells(1).Value)
        End If
    End Sub

    Private Sub cboTipo_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles cboTipo.SelectedIndexChanged
        If cboTipo.Text = "CREDITO" Then
            cboEstado.Text = "EN PROCESO"
            cbxVto.Checked = True
            cbxVto.Enabled = False
        Else
            cboEstado.Text = "PAGADA"
            cbxVto.Checked = False
            cbxVto.Enabled = False
        End If
    End Sub

    Private Sub dgvdetalle_Click(sender As System.Object, e As System.EventArgs) Handles dgvdetalle.Click
        If dgvdetalle.SelectedRows.Count > 0 Then
            CargarComprasDetalle(dgvdetalle.SelectedRows(0).Cells(1).Value)
        End If
    End Sub

End Class